﻿
using System;
using System.Collections.Generic;
using Dora.Services.AdminUser.Entities;
using SqlSugar;
using System.Threading.Tasks;
using Dora.Orm.SqlSugarCore.UnitOfWork;
using Surging.Core.Common;
using Surging.Core.CPlatform.Ioc;

namespace Dora.Services.AdminUser.Repository.Repositorys
{

    /// <summary>
    /// 角色权限映射表仓储层
    /// </summary>
    public class RolePermissionMapRepository : BaseRepository
    {
        private ISugarUnitOfWork _unitOfWork;
        public RolePermissionMapRepository(ISugarUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<int> DeleteByRoleIdAndPermissionIdList(Guid RoleId, List<int> PermissionIdList)
        {
            var result = await _unitOfWork.ModifyClient.Deleteable<RolePermissionMapEntity>().Where(p => p.RoleId == RoleId && PermissionIdList.Contains(p.PermissionId)).ExecuteCommandAsync();

            return result;
        }

        public async Task<int> CreateRange(List<RolePermissionMapEntity> list)
        {
            var result = await _unitOfWork.ModifyClient.Insertable(list.ToArray()).ExecuteCommandAsync();
            return result;
        }
        /// <summary>
        /// 通过权限Id获取权限所属的角色,带名字
        /// </summary>
        /// <param name="EmployeeIdList"></param>
        /// <returns></returns>
        public async Task<List<RolePermissionMapEntity>> GetListByPermissionId(int PermissionId)
        {
            var result = await _unitOfWork.QueryClient.Queryable<RolePermissionMapEntity, RoleEntity>((erp, er) => new object[] {
                    JoinType.Inner, erp.RoleId == er.Id,
                })
                .Where((erp, er) => erp.PermissionId == PermissionId && er.IsDeleted == 0)
                .Select((erp, er) => new { erp.PermissionId, erp.RoleId, er.Name }).Distinct().ToListAsync();
            List<RolePermissionMapEntity> list = new List<RolePermissionMapEntity>();
            if (result?.Count > 0)
            {
                //result = result..ToList();
                foreach (var item in result)
                {
                    var edm = new RolePermissionMapEntity();
                    edm.PermissionId = item.PermissionId;
                    edm.RoleId = item.RoleId;
                    edm.RoleName = item.Name;
                    list.Add(edm);
                }
            }
            return list;
        }
    }
}
